<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useMessage } from "@/hooks/useMessage";
import { useVModel } from "@vueuse/core";
import { setWarehouseAdd, setWarehouseUpdate } from "@/api/warehouse";
import AddressCascader from "@/components/AddressCascader";
import { warehouseStatus } from "@/utils/staticData";
import { getDictList } from "@/api/dict";
import ChargerSelect from "@/components/ChargerSelect";

const { createConfirm } = useMessage();

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  disabled: {
    // 是否只是查看
    type: Boolean,
    default: false
  },
  row: {
    type: Object,
    default: () => {}
  }
});
const emits = defineEmits(["visible", "update:visible", "submit"]);
const isShow = useVModel(props, "visible", emits);
const form = ref({
  warehouseCode: "", // 仓库编码【系统自动生成】
  warehouseName: "", // 仓库名称
  warehouseType: "", // 仓库类型
  provinceCode: "", // 省
  cityCode: "", // 市
  areaCode: "", // 区
  address: "", // 详细地址
  leaderUserId: "", // 负责人
  receiveMobile: "", // 联系方式
  status: 1, // 状态
  provinceName: "", // 省
  cityName: "", // 市
  areaName: "", // 区
  leaderUserName: "" // 负责人
});

const formRef = ref(null);

const validateAddress = (rule, value, callback) => {
  if (!form.value.provinceCode) {
    callback(new Error("请选择省"));
  } else if (!form.value.cityCode) {
    callback(new Error("请选择市"));
  } else if (!form.value.areaCode) {
    callback(new Error("请选择区"));
  } else if (!value) {
    callback(new Error("请选择仓库地址"));
  } else {
    callback();
  }
};

const rules = ref({
  warehouseName: [
    { required: true, message: "请输入仓库名称", trigger: "blur" }
  ],
  warehouseType: [
    { required: true, message: "请选择仓库类型", trigger: "blur" }
  ],
  status: [{ required: true, message: "请选择仓库状态", trigger: "blur" }],
  address: [{ required: true, validator: validateAddress, trigger: "blur" }],
  leaderUserId: [{ required: true, message: "请输入负责人", trigger: "blur" }],
  receiveMobile: [
    { required: true, message: "请输入联系方式", trigger: "blur" }
  ]
});

const inventoryType = ref([]);

onMounted(() => {
  if (props.row && Object.keys(props.row).length !== 0) {
    form.value = { ...props.row };
  }

  getDictList({ dictCode: "WAREHOUSE_TYPE" }).then(res => {
    inventoryType.value = res.data || [];
  });
});

watch(
  () => props.row,
  newVal => {
    form.value = {
      ...newVal
    };
  },
  { deep: true }
);

watch(
  () => isShow.value,
  newVal => {
    if (!newVal) {
      resetForm();
    } else {
      form.value = { ...props.row };
    }
  }
);

// 重置表单
const resetForm = () => {
  form.value = {
    warehouseCode: "",
    warehouseName: "",
    warehouseType: "",
    provinceCode: "",
    cityCode: "",
    areaCode: "",
    address: "",
    leaderUserId: "",
    receiveMobile: "",
    status: 1,
    provinceName: "",
    cityName: "",
    areaName: "",
    leaderUserName: ""
  };
};

const handleClose = (done?: () => void) => {
  let flag = false;
  for (const key in form.value) {
    if (key === "status" && form.value[key] === 1) {
      continue;
    }
    if (!!form.value[key]) flag = true;
  }
  if (flag && !props.row?.id) {
    createConfirm({
      message: "确定关闭吗？",
      center: false
    }).then(() => {
      emits("update:visible", false);
      done && done();
    });
  } else {
    emits("update:visible", false);
    done && done();
  }
};

const handleSubmit = () => {
  if (props.disabled) {
    emits("update:visible", false);
    return;
  }
  formRef.value.validate(valid => {
    if (valid) {
      if (props.row?.id) {
        setWarehouseUpdate({ ...form.value }).then(res => {
          if (res.code === 0) {
            emits("submit");
            emits("update:visible", false);
          }
        });
      } else {
        setWarehouseAdd({ ...form.value }).then(res => {
          if (res.code === 0) {
            emits("submit");
            emits("update:visible", false);
          }
        });
      }
    }
  });
};
</script>

<template>
  <el-dialog
    v-model="isShow"
    :title="props.row?.id ? '编辑仓库' : '新增仓库'"
    width="766px"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="pt-[24px] pl-[8px] pr-[4px]">
      <el-form
        ref="formRef"
        :model="form"
        label-width="92px"
        inline
        :rules="rules"
      >
        <section class="form-container mb-[8px]">
          <div class="font-bold text-14px/[22px] mb-[16px]">仓库信息</div>
          <el-form-item label="仓库编码" disabled prop="warehouseCode">
            <el-input
              v-if="!disabled"
              v-model="form.warehouseCode"
              disabled
              placeholder="系统自动带入"
            />
            <span v-else>{{ form.warehouseCode }}</span>
          </el-form-item>
          <el-form-item class="mr-[0px]" label="仓库名称" prop="warehouseName">
            <el-input
              v-if="!disabled"
              v-model="form.warehouseName"
              placeholder="请输入"
            />
            <span v-else>{{ form.warehouseName }}</span>
          </el-form-item>
          <el-form-item label="仓库类型" prop="warehouseType">
            <el-select
              v-if="!disabled"
              v-model="form.warehouseType"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="(item, index) in inventoryType"
                :key="index"
                :value="item.dictLabelValue"
                :label="item.dictLabelName"
              />
            </el-select>
            <span v-else>{{
              inventoryType.find(
                item => item.dictLabelValue === form.warehouseType
              )?.dictLabelName
            }}</span>
          </el-form-item>
          <el-form-item class="mr-[0px]" label="仓库状态" prop="status">
            <el-radio-group v-if="!disabled" v-model="form.status">
              <el-radio
                v-for="(item, index) in warehouseStatus"
                :key="index"
                :value="item.value"
                :label="item.label"
              />
            </el-radio-group>
            <span v-else>{{
              warehouseStatus.find(item => item.value === form.status)?.label
            }}</span>
          </el-form-item>
          <el-form-item
            class="mr-[0px] width-[100%] pr-[12px] address-item"
            label="仓库地址"
            prop="address"
            required
          >
            <AddressCascader
              v-if="!disabled"
              v-model:provinceCode="form.provinceCode"
              v-model:cityCode="form.cityCode"
              v-model:areaCode="form.areaCode"
              v-model:address="form.address"
            />
            <span v-else>{{
              form.provinceName + form.cityName + form.areaName + form.address
            }}</span>
          </el-form-item>
        </section>
        <section class="mb-[8px]">
          <div class="font-bold text-14px/[22px] mb-[16px]">仓管信息</div>
          <el-form-item label="负责人" prop="leaderUserId">
            <ChargerSelect
              v-model:value="form.leaderUserId"
              :disabled="disabled"
              :leaderUserName="form.leaderUserName"
              :isNeedTab="true"
            />
          </el-form-item>
          <el-form-item class="mr-[0px]" label="联系方式" prop="receiveMobile">
            <el-input
              v-if="!disabled"
              v-model="form.receiveMobile"
              placeholder="请输入"
            />
            <span v-else>{{ form.receiveMobile }}</span>
          </el-form-item>
        </section>
      </el-form>
    </div>
    <template #footer>
      <div class="flex flex-row justify-end">
        <el-button type="primary" @click="handleSubmit">{{
          !disabled ? "提交" : "确定"
        }}</el-button>
        <el-button v-if="!disabled" @click="() => handleClose()"
          >取消</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-form--inline .el-form-item {
  margin-right: 12px;
}
.el-input {
  --el-input-width: 256px !important;
}
.el-select {
  --el-select-width: 256px !important;
}
.form-container {
  .address-item {
    width: 100%;
    margin-right: 0px;
  }
}
</style>
